import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:image_picker/image_picker.dart';
import 'package:kxy_flutter_app/components/loading_widget.dart';
import 'package:kxy_flutter_app/helper/http.dart';
import 'package:kxy_flutter_app/r.dart';

class ImagePickerWidget extends StatelessWidget {
  final String initUrl;
  final double aspectRatio;
  final Function(String) uploaded;
  final double borderRadius;
  final int quality;

  const ImagePickerWidget({
    Key key,
    this.initUrl,
    this.uploaded,
    this.aspectRatio = 16 / 9,
    this.borderRadius = 5,
    this.quality = 80,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: networkImage(context),
      onTap: () async {
        if (uploaded == null) return;
        File file = await ImagePicker.pickImage(source: ImageSource.gallery);

        if (quality < 100) {
          file = await FlutterNativeImage.compressImage(
            file.path,
            quality: quality,
          );
        }
        if (file == null) return;
        var url = await Http.instance.uploadFile(file);
        uploaded(url);
      },
    );
  }

  Widget networkImage(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    return Container(
      decoration: boxDecoration(),
      width: width,
      child: AspectRatio(
        aspectRatio: aspectRatio,
        child: ClipRRect(
          borderRadius: BorderRadius.circular(borderRadius),
          child: CachedNetworkImage(
            fit: BoxFit.cover,
            imageUrl: initUrl ?? '',
            placeholder: (cxt, _) => LoadingWidget(),
            errorWidget: (cxt, _, __) => placeholder(),
          ),
        ),
      ),
    );
  }

  Widget placeholder() {
    return Padding(
      padding: EdgeInsets.all(15),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Padding(
            padding: EdgeInsets.only(bottom: 10),
            child: Image.asset(
              R.assetsImgNoImage,
              height: 60,
              color: Colors.black38,
            ),
          ),
          Text(
            '上传图片',
            style: TextStyle(color: Colors.black38),
          ),
        ],
      ),
    );
  }

  BoxDecoration boxDecoration() {
    return BoxDecoration(
      color: Color.fromRGBO(240, 240, 240, 1),
      borderRadius: BorderRadius.circular(borderRadius),
      boxShadow: [
        BoxShadow(
          color: Color.fromRGBO(240, 240, 240, 1),
          blurRadius: 2,
          offset: Offset(2, 2),
        ),
        BoxShadow(
          color: Color.fromRGBO(240, 240, 240, 1),
          blurRadius: 2,
          offset: Offset(2, 2),
        ),
      ],
    );
  }
}
